<template>
    <div>
        <!-- 标题部分 -->
        <div class="Header">
            <el-select v-model="addTest.startRange" placeholder="请选择起始范围">
                <el-option v-for="(item,index) in chapters" :key="'select-'+index"
                    :label="item.chapterNumber+item.description" :value="item.id"></el-option>
            </el-select>
            <el-input placeholder="请输入标题" v-model="addTest.title">
            </el-input>
            <el-select v-model="addTest.endRange" placeholder="请选择截至范围">
                <el-option v-for="(item,index) in chapters" :key="'select_end'+index"
                    :label="item.chapterNumber+item.description" :value="item.id"></el-option>
            </el-select>
        </div>
        <!-- 主体部分 -->
        <div class="main">
            <div v-for="(item,index) in addTest.fileUpload" :key="index" class="main_li">
                <span class="questionorder">第{{item.order}}题：</span>
                <el-input type="textarea" :autosize="{ minRows: 2}" maxlength="255" placeholder="请输入问题描述"
                    class="firstinput" v-model="item.description"></el-input>
                <el-input placeholder="请输入分值" class="lastinput" v-model.number="item.score"></el-input>
                <div>
                    <el-button type="danger" @click="delectQuestion(item.order)">删除题目</el-button>
                    <el-button type="success" @click="addQuestion">添加题目</el-button>
                </div>
            </div>
        </div>

        <!-- 提交部分 -->
        <div class="submit">
            <el-button type="primary" @click="submit">提交</el-button>
        </div>

        <!-- 确认对话框 -->
        <el-dialog title="提交试题2" :visible.sync="dialogVisible" width="30%" :before-close="handleClose">
            <div>
                <span>共{{addTest.fileUpload.length}}道题，共{{fileUploadscores}}分</span>
            </div>
            <!-- 起始时间和结束时间选择 -->
            <span>开始时间: </span>
            <el-date-picker class="date-picker" v-model="addTest.startTime" type="datetime" placeholder="选择开始时间">
            </el-date-picker><br>
            <p></p>
            <span>结束时间: </span>
            <el-date-picker class="date-picker" v-model="addTest.endTime" type="datetime" placeholder="选择结束时间">
            </el-date-picker><br>
            <p></p>
            <span>班级选择: </span>
            <!-- 班级选择 -->
            <el-select v-model="addTest.classes" multiple placeholder="请选择班级">
                <el-option v-for="item in classes" :key="item.id" :label="item.className" :value="item.id">
                </el-option>
            </el-select>

            <span slot="footer" class="dialog-footer">
                <el-button type="primary" @click="addTestTo">提交</el-button>
            </span>
        </el-dialog>
    </div>
</template>
<script>
    export default {
        watch: {
            'addTest.fileUpload': {
                handler(newVal, oldVal) {
                    this.computeScores()
                },
                deep: true,
                immediate: true
            },  
        },
        created() {
            this.getChapter()
        },
        mounted() {
            this.getCalssList()
        },
        data() {
            return {
                classes: null,
                chapters: null,
                addTest: {
                    title: "",                      // 试卷标题
                    workType: 2,                    // 测试种类，2表示人工评判
                    startRange: null,               // 开始范围
                    endRange: null,                 // 结束范围
                    fileUpload: [{
                        order: 1,
                        description: "",
                        score: null,
                    },],
                    classes: [],                    // 班级选择
                    startTime: null,                // 开始时间
                    endTime: null,                  // 结束时间
                },
                fileUploadscores:null,              // 总分
                dialogVisible:false
            };
        },

        methods: {
            // 时间格式转化
            formatDate(date) {
                const year = date.getFullYear();
                const month = String(date.getMonth() + 1).padStart(2, '0'); // 月份是从0开始的，所以要加1  
                const day = String(date.getDate()).padStart(2, '0');
                const hours = String(date.getHours()).padStart(2, '0');
                const minutes = String(date.getMinutes()).padStart(2, '0');
                const seconds = String(date.getSeconds()).padStart(2, '0');

                // 注意：这里返回的是本地时间的字符串，不是UTC时间的字符串  
                return `${year}-${month}-${day}T${hours}:${minutes}:${seconds}`;
            },
            // 获取所有章节
            async getChapter() {
                const { data: res } = await this.$axios.get("/chapter/getChapter")
                this.chapters = res.data
            },
            // 获取班级信息
            async getCalssList() {
                const { data: res } = await this.$axios.get("/getClasses")
                this.classes = res.data
            },

            // 重新排序，根据数组的先后顺序
            ordersort() {
                for (let i = 0; i < this.addTest.fileUpload.length; i++) {
                    this.addTest.fileUpload[i].order = i + 1
                }
            },
            // 添加题目
            addQuestion() {
                this.addTest.fileUpload.push({ order: null, description: "", score: null, })
                this.ordersort()
            },

            // 删除题目
            delectQuestion(order) {
                if (this.addTest.fileUpload.length === 1) {
                    return this.$message("这个不能再删除了")
                }
                this.addTest.fileUpload = this.addTest.fileUpload.filter(item => item.order != order)
                this.ordersort()
            },

            // 计算总分
            computeScores() {
                var s = 0;
                for (let i = 0; i < this.addTest.fileUpload.length; i++) {
                    s = s + this.addTest.fileUpload[i].score
                }
                this.fileUploadscores=s
            },
            // 关闭前的操作
            handleClose(){
                this.addTest.classes=[]
                this.addTest.startTime=null
                this.addTest.endTime=null
                this.dialogVisible=false
            },
            // 提交测试题
            submit() {
                if (this.addTest.title === "") {
                    return this.$message("请输入标题")
                }
                if (this.addTest.startRange === null || this.addTest.endRange === null) {
                    return this.$message("请输入考试范围")
                }

                for (let i = 0; i < this.addTest.fileUpload.length; i++) {
                    if (this.addTest.fileUpload[i].description === "") {
                        return this.$message("请完善题目信息")
                    }
                    if (this.addTest.fileUpload[i].score === null||isNaN(Number(this.addTest.fileUpload[i].score))) {
                        return this.$message("请完善题目分数")
                    }
                }
                this.dialogVisible=true
            },

            // 发起网络请求
            async addTestTo() {
                if(this.addTest.startTime===null||this.addTest.endTime===null||
                this.addTest.classes.length===0){
                    return this.$message("请完善资料")
                }
                this.addTest.startTime = this.formatDate(this.addTest.startTime)
                this.addTest.endTime = this.formatDate(this.addTest.endTime)
                const { data: res } = await this.$axios.put('/publishtest/addTest2', this.addTest)
                if(res.code===303){
                    return this.$message.error("时间格式不正确")
                }
                if(res.code===200){
                    this.handleClose()
                    return this.$message.success("发布成功")
                }
                return this.$message.error("网络错误")
            }

        }
    }
</script>

<style lang="less" scoped>
    /* 标题部分 */
    .Header {
        display: flex;
        justify-content: center;

        .el-input {
            margin: auto 20px;
            width: 400px;
        }

        padding-bottom: 10px;
        margin-bottom: 10px;
        border-bottom: 10px double #76aca9;
    }

    /* 主体部分 */
    .main {
        .main_li {
            margin-top: 20px;

            .questionorder {
                line-height: 100%;
                text-align: center;
                width: 100px;
            }

            display: flex;
            justify-content: space-between;

            .firstinput {
                width: 600px;
            }

            .lastinput {
                width: 110px;
            }

            div {
                margin-right: 50px;
            }
        }
    }

    /* 提交部分 */
    .submit {
        margin-top: 30px;
        padding-top: 10px;
        border-top: 1px solid #000;
        text-align: center;
    }

    /* 对话框*/
    .el-dialog{
        div{
            margin-bottom: 10px;
        }
        .el-date-picker{
            margin-bottom: 40px;
        }

        .el-select{
            width: 70%;
        }
    }
</style>